package com.xsomnus.network_programming.netty.heartbeat;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;


/**
 * @author 叶小夏
 * @since 2019-08-16 17:09
 */
public class TcpClient {

    private String host;
    private int port;
    private Bootstrap bootstrap;
    private Channel channel;
    private volatile boolean stoppable = true;


    public TcpClient(String host, int port) {
        this.port = port;
        this.host = host;
        init();
    }

    public void connect() {
        synchronized (bootstrap) {
            ChannelFuture future = bootstrap.connect(host, port);
            future.addListener(getConnectionListener());
            this.channel = future.channel();
        }
    }

    private ChannelFutureListener getConnectionListener() {
        return future -> {
            if (!future.isSuccess()) {
                future.channel().pipeline().fireChannelInactive();
            } else {
                SocketAddress socketAddress = channel.localAddress();
                System.out.println(socketAddress.toString());
            }
        };
    }

    private void init() {
        EventLoopGroup group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_SNDBUF, 1024)
                .handler(new ClientHandlerInitializer(TcpClient.this));
    }


    static ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    static LongAdder counter = new LongAdder();
    public static void main(String[] args) {
        TcpClient client = new TcpClient("localhost", 2222);
        client.connect();
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            counter.increment();
            client.channel.writeAndFlush(Unpooled.copiedBuffer("Heloolo"+counter.intValue(), StandardCharsets.UTF_8));
        }, 1, 2, TimeUnit.SECONDS);

//        while (client.stoppable) {
//            Scanner scanner = new Scanner(System.in);
//            String line = scanner.nextLine();
//            int loop = Integer.parseInt(line);
//            for (int i = 0; i < loop; i++) {
//                client.channel.writeAndFlush(Unpooled.copiedBuffer("Heloolo" + i, StandardCharsets.UTF_8));
//            }
//        }
    }
}
